package com.shgbit.tdd.args;

import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liuyong
 * @date 2020-04-07 16:08
 */
public class Command {

    private Map<String, String> commandMap;
    private Schemas schemas;

    public Command(String commandStr, Schemas schemas) {
        this.commandMap = init(commandStr, schemas);
        this.schemas = schemas;
    }

    public Schemas getSchemas() {
        return schemas;
    }

    private HashMap<String, String> init(String commandStr, Schemas schemas) {
        if (StringUtils.isEmpty(commandStr)) {
            throw new IllegalArgumentException("请传入命令");
        }
        if (schemas == null) {
            throw new IllegalArgumentException("请传入Schemas");
        }
        HashMap<String, String> commandMap = new HashMap<>();
        String[] commands = commandStr.split(" ");
        int length = commands.length;
        for (int i = 0; i < length - 1; i++) {
            if (schemas.isKey(commands[i])) {
                if (schemas.isKey(commands[i + 1])) {
                    commandMap.put(commands[i].substring(1), null);
                } else {
                    commandMap.put(commands[i].substring(1), commands[i + 1]);
                }
            }
        }
        if (schemas.isKey(commands[length - 1])) {
            commandMap.put(commands[length - 1].substring(1), null);
        }
        return commandMap;
    }

    public String get(String key) {
        return commandMap.get(key);
    }
}
